package com.zerous.simplerts;

import android.view.*;
import android.content.*;
import android.graphics.*;

public class GameView extends SurfaceView implements Runnable
{
	volatile boolean running;
	
	Thread gameThread;
	SurfaceHolder holder;
	Canvas canvas;
	Bitmap framebuffer;
	Game game;
	long lastFrameTime = System.nanoTime();
	
	public GameView(Game game, Bitmap frambuffer)
	{
		super(game);
		holder = this.getHolder();
		this.framebuffer = frambuffer;
		this.game = game;
	}

	@Override
	public void run()
	{
		long startTime = System.nanoTime();
		while(running)
		{
			if(!holder.getSurface().isValid()) continue;
			
			float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
			startTime = System.nanoTime();
			
			
			canvas = holder.lockCanvas();
			
			Zef.graphics.update(deltaTime);
			game.currentScreen.update(deltaTime);
			game.currentScreen.draw(); 
			
			canvas.drawBitmap(framebuffer, 0, 0, null);
			
			if(canvas != null)
			{
				holder.unlockCanvasAndPost(canvas);
			}
		}
	}

	public void resume()
	{
		running = true;
		gameThread = new Thread(this);
		gameThread.start();
	}

	public void pause()
	{
		running = false;
		while(true)
		{
			try
			{
				gameThread.join();
				break;
			}
			catch(InterruptedException e)
			{

			}
		}
	}
}
